package dao.impl;


import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    public List<User> findAll()
    {
        List<User> users=new ArrayList<>();
        ResultSet ResultSet=null;
        PreparedStatement PreparedStatement=null;
        Connection Connection=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            String URL = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            String USER = "root";
            String PASSWORD = "ccylyw0589";
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            /*if (connection != null) {
                System.out.println("连接成功");
            }*/
            //3.写sql
            String sql = "select * from user";
            //4.预编译sql
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //5.有参设参
            //6.执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            //7.遍历结果集
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                //把对象添加到集合中
                users.add(user);
            }
            return users;

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            try{
                if(ResultSet!=null){
                    ResultSet.close();
                }
                if(PreparedStatement!=null)
                    PreparedStatement.close();
                if(Connection!=null)
                    ResultSet.close();
            }catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    }
}
